package org.budo.weixin.work.api;

import java.io.Serializable;

import org.budo.weixin.work.api.entity.WorkWeixinToken;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

/**
 * @author lmw
 */
@Getter
@Setter
@Accessors(chain = true)
@ToString
public abstract class AbstractWorkWeixinApi implements WorkWeixinApi, Serializable {
    private static final long serialVersionUID = 3933513503758005642L;

    private WorkWeixinToken workWeixinToken;

    private String corpId;

    private String corpSecret;

    private String approvalToken;

    private String approvalEncodingAesKey;

    public WorkWeixinApi setAccessToken(String accessToken) {
        this.setWorkWeixinToken(new WorkWeixinToken(accessToken, 24 * 60 * 60));
        return this;
    }

    protected String accessToken() {
        if (null != this.getWorkWeixinToken() && this.getWorkWeixinToken().isOk()) {
            return this.getWorkWeixinToken().getAccessToken();
        }

        this.workWeixinToken = this.getToken(this.getCorpId(), this.getCorpSecret());

        if (null == this.workWeixinToken) {
            throw new IllegalArgumentException("#47 workWeixinToken=" + this.workWeixinToken + ", this=" + this);
        }

        return this.workWeixinToken.getAccessToken();
    }
}